﻿using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Components.WebView.Maui;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.FileProviders;
using MyToDoList.Common.DependencyInjection;
using MyToDoList.Data;
using System.Reflection;

namespace MyToDoList;

public static class MauiProgram
{
	public static MauiApp CreateMauiApp()
	{
		var builder = MauiApp.CreateBuilder();
		builder
			.UseMauiApp<App>()
			.ConfigureFonts(fonts =>
			{
				fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
			});
		ConfigureConfiguration(builder);
        ConfigureContainer(builder);

        builder.Services.AddMauiBlazorWebView();
        builder.Services.AddMasaBlazor();
#if DEBUG
		builder.Services.AddBlazorWebViewDeveloperTools();
#endif

		return builder.Build();
	}

    private static void ConfigureConfiguration(MauiAppBuilder builder)
    {
		// 嵌入资源的配置文件
        var assembly = typeof(App).GetTypeInfo().Assembly;
        builder.Configuration.AddJsonFile(new EmbeddedFileProvider(assembly), "appsettings.json", optional: false, false);
        // App的Resource配置文件
        var stream = FileSystem.OpenAppPackageFileAsync("appsettings.svg").ConfigureAwait(false).GetAwaiter().GetResult();
        builder.Configuration.AddJsonStream(stream);
    }

	private static void ConfigureContainer(MauiAppBuilder builder)
	{
        builder.ConfigureContainer(new AutofacServiceProviderFactory(opt => {
	
			// 瞬态
			opt.RegisterAssemblyTypes(typeof(MauiProgram).Assembly)
				.Where(t => typeof(ITransientInterface).IsAssignableFrom(t) && t.IsClass && !t.IsAbstract)
                .AsSelf()		// 注册类自身
                .AsImplementedInterfaces()	// 注册类实现的所有接口
				.InstancePerDependency();
			// 单例
            opt.RegisterAssemblyTypes(typeof(MauiProgram).Assembly)
                .Where(t => 
				typeof(ISingletonInterface).IsAssignableFrom(t) && t.IsClass && !t.IsAbstract)
				.AsSelf()		// 注册类自身
                .AsImplementedInterfaces()	// 注册类实现的所有接口
                .SingleInstance();
		}));
    }
}
